import React, { useRef } from 'react';

import { PlusOutlined } from '@ant-design/icons';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { FormInstance, ProFormInstance } from '@ant-design/pro-form';
import { Button, message } from 'antd';

interface Column {
  key?: string;
  title: string;
  dataIndex: string;
  valueType?: string;
  valueEnum?: any;
  width?: string | number;
  render?: any;
  readonly?: boolean;
  formItemProps?: any;
  search?: boolean;

  initialValue?: any;
  fieldProps?: any;
  request?: Promise<any>;
}
interface Props {
  onChange?: (event: number | string) => void;
  request?: any;
  columns: Column[];
  btnText: string | '';
  title: string | '';
  initialValues: any;
  width: number | null;
  formRef?:
    | React.MutableRefObject<ProFormInstance<any> | undefined>
    | React.RefObject<ProFormInstance<any> | undefined>;
}

const FormModalBtn: React.FC<Props> = (props) => {
  let {
    columns,
    request,
    btnText,
    title,
    initialValues,
    width,
    onChange,
    formRef,
  } = props;
  if (formRef == undefined) {
    // @ts-ignore
    formRef = useRef<FormInstance>();
  }

  return (
    <BetaSchemaForm
      width={width != null ? width : 500}
      layoutType="ModalForm"
      title={title}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          {btnText}
        </Button>
      }
      initialValues={initialValues}
      formRef={formRef}
      onFinish={(values) => {
        return new Promise((resolve, reject) => {
          console.log(values);
          if (request != null) {
            // @ts-ignore
            request(values)
              .then((res: any) => {
                console.log('操作', res);
                let success = res.success;
                if (success) {
                  message.success('操作成功');
                  if (onChange) {
                    onChange(res);
                  }
                  formRef.current?.resetFields();
                  resolve(res);
                } else {
                  message.error('操作失败');
                  reject(res);
                }
              })
              .catch((error: any) => {
                message.error('操作失败');
                reject(error);
              });
          }
        });
      }}
      columns={columns}
    />
  );
};
export default FormModalBtn;
